package net.goutalk.glcs.module.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.utils.RedisUtil;
import net.goutalk.glcs.module.system.entity.DictionaryDetail;
import net.goutalk.glcs.module.system.entity.DictionaryItem;
import net.goutalk.glcs.module.system.mapper.DictionarydetailMapper;
import net.goutalk.glcs.module.system.mapper.DictionaryitemMapper;
import net.goutalk.glcs.module.system.service.IDictionaryitemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.goutalk.glcs.module.system.vo.DictionaryDetailVo;
import net.goutalk.glcs.module.system.vo.DictionaryItemDetailTreeVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典项目 服务实现类
 * </p>
 *
 * @author tanyujie
 * @since 2022-03-17
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictionaryitemServiceImpl extends ServiceImpl<DictionaryitemMapper, DictionaryItem> implements IDictionaryitemService {

    private RedisUtil redisUtil;

    private DictionarydetailMapper dictionarydetailMapper;

    @Override
    public List<DictionaryItemDetailTreeVo> getTree() {

        List<DictionaryItem> itemList = list();
        List<DictionaryDetail> detailList = dictionarydetailMapper.selectList(null);

        List<DictionaryItemDetailTreeVo> result = new ArrayList<>();

        for (DictionaryItem dictionaryItem : itemList) {
            List<DictionaryDetail> child = detailList.stream().filter(x -> x.getItemId().equals(dictionaryItem.getId())).collect(Collectors.toList());
            DictionaryItemDetailTreeVo vo = BeanUtil.toBean(dictionaryItem, DictionaryItemDetailTreeVo.class);
            vo.setChildren(BeanUtil.copyToList(child, DictionaryDetailVo.class));
            result.add(vo);
        }

        return result;
    }

    @Async
    public void loadCaches() {
        log.info("GLCS: 加载所有数据字典详情缓存开始");
        List<DictionaryItem> list = this.list();
        redisUtil.set(GlobalConstant.DIC_ITEM_CACHE_KEY, list);
        log.info("GLCS: 加载所有数据字典详情缓存结束");
    }
}
